<?php
/**
 * Created by PhpStorm.
 * User: jacob
 * Date: 18-9-3
 * Time: 下午12:12
 */
namespace DB;

use Config\Time;
use MongoDB\BSON\ObjectID;
use MongoDB\Driver\BulkWrite;
use MongoDB\Driver\Query;
use Tiny\Logger;

class AccountOrgInfo{
  public $_id;
  public $name;
  public $password;
  public $create_at;
  public $last_login_at;
  public $last_login_ip;

  public function toArray(){
    $array = json_decode(json_encode($this),true);
    return array_filter($array,function ($k,$v){
      /**
       * @var $k $value
       * @var $v $key
       */
      return $k != null && $v != null;
    },ARRAY_FILTER_USE_BOTH);
  }
}

class AccountOrg extends Mongodb {
  const uid = "_id";
  const name = "name";
  const password = "password";
  const create_at = "create_at";
  const last_login_at = "last_login_at";
  const last_login_ip = "last_login_ip";

  public function __construct(string $uid = "") {
    parent::__construct("AccountOrg");
    $this->uid = $uid;
  }

  /**
   * @param AccountOrgInfo $info
   * @return bool
   */
  public function insert(AccountOrgInfo $info):bool {
    $manager = $this->getManager();
    $bulk = new BulkWrite();
    if (!isset($info->_id)){
      $info->_id = new ObjectID()."";
    }
    if (!isset($info->create_at)){
      $info->create_at = Time::millisecond();
    }
    $bulk->insert($info->toArray());
    try{
      $manager->executeBulkWrite($this->getNamespace(),$bulk);
      return true;
    }catch (\Exception $exception){
      Logger::getInstance()->fatal("insert AccountOrg failed,code is 
      ".$exception->getCode().",msg is ".$exception->getMessage());
      return false;
    }
  }

  /**
   * @param string $name
   * @return bool
   */
  public function buildByAccount(string $name):bool {
    $filter = [self::name => $name];
    $options["projection"] = [self::uid => 1];
    $manager = $this->getManager();
    $cursor = $manager->executeQuery($this->getNamespace(),new Query($filter,$options));
    $value = $cursor->toArray();
    if (count($value) == 0){
      return false;
    }
    $this->uid = $value[0]->{self::uid};
    return true;
  }

  /**
   * @param string $password
   * @return bool
   */
  public function verity(string $password):bool {
    $filter = [self::uid => $this->getUid()];
    $options['projection'] = [self::password => 1];
    $manager = $this->getManager();
    $cusor = $manager->executeQuery($this->getNamespace(),new Query($filter,$options));
    $value = $cusor->toArray();
    if (count($value) == 0){
      return false;
    }
    return password_verify(md5($password),$value[0]->{self::password});
  }

  /**
   * @param string $password
   * @return string
   */
  public function encryptPass(string $password):string {
    return password_hash(md5($password),PASSWORD_BCRYPT,['cost' => 10]);
  }

  public function getUid(){
    return $this->uid;
  }

  private $uid;
}